<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/10/26
 * Time: 12:18 AM
 */

namespace App\Library\Mall;


use App\Library\AuthenticatedUser;
use App\WeChat\Pay\JsApiPay;
use App\WeChat\Response\UnifiedResponse;
use Illuminate\Http\Request;

trait WxPayTrait
{
    use AuthenticatedUser;

    protected function getPayConfig($order, $openid)
    {

        $trade = $order->trade;
        $out_trade_no = createTradeNo();
        $jsapiPay = new JsApiPay();
        $jsapiPay->setBody($trade->body)
                //正式支付金额
                //->setTotalFee($trade->total_amount*100)
                //测试金额
                ->setTotalFee(1)
                ->setOutTradeNo($out_trade_no)
                ->setOpenid($openid);
        $res = new UnifiedResponse($this->payment->order->unify($jsapiPay->getBizContent()));
        if ($res->tradeSuccess()) {
            $trade->update(['out_trade_no'=>$out_trade_no]);
            return $this->sendConfigResponse($res);
        } else {
            return $this->sendConfigFailedResponse($res);
        }
    }

    /**
     * @param UnifiedResponse $unifiedResponse
     * @return \Illuminate\Http\JsonResponse
     */
    protected function sendConfigResponse(UnifiedResponse $unifiedResponse)
    {
        return ajaxReturn(['config'=>$this->payment->jssdk->bridgeConfig($unifiedResponse->prepayId())]);
    }

    /**
     * @param UnifiedResponse $unifiedResponse
     * @return \Illuminate\Http\JsonResponse
     */
    protected function sendConfigFailedResponse(UnifiedResponse $unifiedResponse)
    {
        if ($unifiedResponse->errCode())
        {
            return ajaxError($unifiedResponse->errCode(), $unifiedResponse->errCodeDes());
        }
        return ajaxError($unifiedResponse->returnCode(), $unifiedResponse->retrunMsg());
    }
}
